<template>
  <div class="process-designer">
    <HeaderNav />
    <div class="designer-container">
      <!-- 左侧组件库 -->
      <div class="components-panel">
        <div class="panel-header">
          <h3>组件库</h3>
        </div>
        <div class="components-list">
          <div
            class="component-item"
            draggable="true"
            @dragstart="onDragStart($event, 'start')"
          >
            <i class="el-icon-video-play"></i>
            <span>开始节点</span>
          </div>
          <div
            class="component-item"
            draggable="true"
            @dragstart="onDragStart($event, 'approval')"
          >
            <i class="el-icon-user"></i>
            <span>审批节点</span>
          </div>
          <div
            class="component-item"
            draggable="true"
            @dragstart="onDragStart($event, 'condition')"
          >
            <i class="el-icon-help"></i>
            <span>条件分支</span>
          </div>
          <div
            class="component-item"
            draggable="true"
            @dragstart="onDragStart($event, 'copy')"
          >
            <i class="el-icon-message"></i>
            <span>抄送节点</span>
          </div>
          <div
            class="component-item"
            draggable="true"
            @dragstart="onDragStart($event, 'end')"
          >
            <i class="el-icon-video-pause"></i>
            <span>结束节点</span>
          </div>
        </div>
      </div>

      <!-- 中间画布区域 -->
      <div class="canvas-panel">
        <div class="canvas-header">
          <el-input
            v-model="processName"
            placeholder="请输入流程名称"
            style="width: 300px;"
          />
          <div class="canvas-actions">
            <el-button type="primary" @click="saveProcess">保存流程</el-button>
            <el-button @click="previewProcess">预览</el-button>
          </div>
        </div>
        <div
          class="canvas-container"
          @drop="onDrop"
          @dragover="onDragOver"
        >
          <!-- 流程节点画布 -->
          <div
            v-for="node in nodes"
            :key="node.id"
            class="process-node"
            :class="node.type"
            :style="{ left: node.x + 'px', top: node.y + 'px' }"
            @click="selectNode(node)"
          >
            <i :class="getNodeIcon(node.type)"></i>
            <span>{{ node.name }}</span>
            <div class="node-actions" v-if="selectedNode && selectedNode.id === node.id">
              <el-button
                type="danger"
                size="small"
                circle
                icon="el-icon-delete"
                @click.stop="deleteNode(node)"
              />
            </div>
          </div>

          <!-- 连接线 -->
          <svg class="connections-svg" v-if="connections.length > 0">
            <line
              v-for="conn in connections"
              :key="conn.id"
              :x1="conn.startX"
              :y1="conn.startY"
              :x2="conn.endX"
              :y2="conn.endY"
              class="connection-line"
            />
          </svg>
        </div>
      </div>

      <!-- 右侧配置面板 -->
      <div class="config-panel" v-if="selectedNode">
        <div class="panel-header">
          <h3>节点配置</h3>
        </div>
        <div class="config-content">
          <el-form label-width="80px" size="small">
            <el-form-item label="节点名称">
              <el-input v-model="selectedNode.name" />
            </el-form-item>

            <el-form-item label="节点类型">
              <el-select v-model="selectedNode.type" disabled>
                <el-option label="开始节点" value="start" />
                <el-option label="审批节点" value="approval" />
                <el-option label="条件分支" value="condition" />
                <el-option label="抄送节点" value="copy" />
                <el-option label="结束节点" value="end" />
              </el-select>
            </el-form-item>

            <!-- 审批节点配置 -->
            <div v-if="selectedNode.type === 'approval'">
              <el-form-item label="审批人">
                <el-select v-model="selectedNode.approvers" multiple placeholder="请选择审批人">
                  <el-option label="管理员" value="admin" />
                  <el-option label="部门经理" value="manager" />
                  <el-option label="普通用户" value="user" />
                </el-select>
              </el-form-item>
              <el-form-item label="审批方式">
                <el-radio-group v-model="selectedNode.approvalType">
                  <el-radio label="and">会签（所有审批人同意）</el-radio>
                  <el-radio label="or">或签（任一审批人同意）</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="超时提醒">
                <el-input-number
                  v-model="selectedNode.timeout"
                  :min="1"
                  :max="168"
                  controls-position="right"
                /> 小时
              </el-form-item>
            </div>

            <!-- 条件分支配置 -->
            <div v-if="selectedNode.type === 'condition'">
              <el-form-item label="条件规则">
                <el-input
                  v-model="selectedNode.condition"
                  type="textarea"
                  placeholder="请输入条件表达式，如：amount > 10000"
                  :rows="3"
                />
              </el-form-item>
            </div>

            <!-- 抄送节点配置 -->
            <div v-if="selectedNode.type === 'copy'">
              <el-form-item label="抄送人">
                <el-select v-model="selectedNode.copyUsers" multiple placeholder="请选择抄送人">
                  <el-option label="管理员" value="admin" />
                  <el-option label="部门经理" value="manager" />
                  <el-option label="普通用户" value="user" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 流程预览对话框 -->
    <el-dialog
      title="流程预览"
      v-model="previewVisible"
      width="60%"
    >
      <div class="preview-content">
        <h3>{{ processName }}</h3>
        <div class="preview-canvas">
          <!-- 简化版流程图预览 -->
          <div
            v-for="node in nodes"
            :key="'preview-' + node.id"
            class="preview-node"
            :class="node.type"
            :style="{ left: node.x + 'px', top: node.y + 'px' }"
          >
            <i :class="getNodeIcon(node.type)"></i>
            <span>{{ node.name }}</span>
          </div>

          <svg class="preview-svg" v-if="connections.length > 0">
            <line
              v-for="conn in connections"
              :key="'preview-' + conn.id"
              :x1="conn.startX"
              :y1="conn.startY"
              :x2="conn.endX"
              :y2="conn.endY"
              class="preview-line"
            />
          </svg>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import HeaderNav from '@/components/HeaderNav.vue'
import { getProcessDetail, createProcess, updateProcess } from '@/api/workflow'
import { useRoute, useRouter } from 'vue-router'

// 响应式数据
const processName = ref('新建流程')
const nodes = ref([])
const connections = ref([])
const selectedNode = ref(null)
const previewVisible = ref(false)
const dragData = ref(null)

// 路由相关
const route = useRoute()
const router = useRouter()
const processId = ref(null)

// 组件挂载时获取流程详情
onMounted(async () => {
  if (route.params.id) {
    processId.value = route.params.id
    await loadProcessDetail(processId.value)
  }
})

// 加载流程详情
const loadProcessDetail = async (id) => {
  try {
    const response = await getProcessDetail(id)

    if (response.code === 200) {
      const process = response.data
      processName.value = process.name
      nodes.value = process.nodes || []
      connections.value = process.connections || []
    } else {
      ElMessage.error(response.message || '获取流程详情失败')
    }
  } catch (error) {
    console.error('获取流程详情失败:', error)
    ElMessage.error('获取流程详情失败')
  }
}

// 节点类型对应的图标
const getNodeIcon = (type) => {
  const icons = {
    start: 'el-icon-video-play',
    approval: 'el-icon-user',
    condition: 'el-icon-help',
    copy: 'el-icon-message',
    end: 'el-icon-video-pause'
  }
  return icons[type] || 'el-icon-question'
}

// 拖拽开始事件
const onDragStart = (event, nodeType) => {
  dragData.value = {
    type: nodeType,
    name: getNodeTypeName(nodeType)
  }
  event.dataTransfer.effectAllowed = 'copy'
}

// 获取节点类型名称
const getNodeTypeName = (type) => {
  const names = {
    start: '开始节点',
    approval: '审批节点',
    condition: '条件分支',
    copy: '抄送节点',
    end: '结束节点'
  }
  return names[type] || '未知节点'
}

// 拖拽事件
const onDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'copy'
}

// 放置事件
const onDrop = (event) => {
  event.preventDefault()

  if (!dragData.value) return

  const rect = event.currentTarget.getBoundingClientRect()
  const x = event.clientX - rect.left - 60
  const y = event.clientY - rect.top - 20

  const newNode = {
    id: Date.now(),
    type: dragData.value.type,
    name: dragData.value.name,
    x: x,
    y: y,
    approvers: [],
    approvalType: 'and',
    timeout: 24,
    condition: '',
    copyUsers: []
  }

  nodes.value.push(newNode)
  dragData.value = null
}

// 选择节点
const selectNode = (node) => {
  selectedNode.value = node
}

// 删除节点
const deleteNode = (node) => {
  const index = nodes.value.findIndex(n => n.id === node.id)
  if (index !== -1) {
    nodes.value.splice(index, 1)
    // 同时删除相关的连接线
    connections.value = connections.value.filter(
      conn => conn.from !== node.id && conn.to !== node.id
    )
  }
  selectedNode.value = null
}

// 保存流程
const saveProcess = async () => {
  if (nodes.value.length === 0) {
    ElMessage.warning('请至少添加一个节点')
    return
  }

  // 检查是否有开始和结束节点
  const hasStart = nodes.value.some(node => node.type === 'start')
  const hasEnd = nodes.value.some(node => node.type === 'end')

  if (!hasStart) {
    ElMessage.warning('请添加开始节点')
    return
  }

  if (!hasEnd) {
    ElMessage.warning('请添加结束节点')
    return
  }

  // 保存流程逻辑
  try {
    const processData = {
      name: processName.value,
      nodes: nodes.value,
      connections: connections.value
    }

    let response
    if (processId.value) {
      // 更新流程
      response = await updateProcess(processId.value, processData)
    } else {
      // 创建流程
      response = await createProcess(processData)
    }

    if (response.code === 200 || response.code === 201) {
      ElMessage.success('流程保存成功')
      // 跳转到流程列表页面
      router.push('/workflow/list')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存流程失败:', error)
    ElMessage.error('保存失败')
  }
}

// 预览流程
const previewProcess = () => {
  if (nodes.value.length === 0) {
    ElMessage.warning('请先添加节点')
    return
  }
  previewVisible.value = true
}
</script>

<style scoped lang="scss">
.process-designer {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.designer-container {
  flex: 1;
  display: flex;
  background-color: #f5f7fa;
}

.components-panel {
  width: 200px;
  background: white;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;

  .panel-header {
    padding: 15px;
    border-bottom: 1px solid #ebeef5;
    h3 {
      margin: 0;
      font-size: 16px;
    }
  }

  .components-list {
    flex: 1;
    padding: 10px;

    .component-item {
      display: flex;
      align-items: center;
      padding: 10px;
      margin-bottom: 8px;
      background: #f5f7fa;
      border-radius: 4px;
      cursor: grab;
      transition: all 0.3s;

      &:hover {
        background: #ecf5ff;
        transform: translateX(5px);
      }

      i {
        margin-right: 8px;
        font-size: 16px;
      }

      span {
        font-size: 14px;
      }
    }
  }
}

.canvas-panel {
  flex: 1;
  display: flex;
  flex-direction: column;

  .canvas-header {
    padding: 15px;
    background: white;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .canvas-container {
    flex: 1;
    position: relative;
    background: #fafafa;
    overflow: auto;
    min-height: 0;

    .process-node {
      position: absolute;
      width: 120px;
      height: 60px;
      border-radius: 6px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      &.start {
        background: #67c23a;
        color: white;
      }

      &.approval {
        background: #409eff;
        color: white;
      }

      &.condition {
        background: #e6a23c;
        color: white;
      }

      &.copy {
        background: #909399;
        color: white;
      }

      &.end {
        background: #f56c6c;
        color: white;
      }

      &:hover {
        transform: scale(1.05);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }

      i {
        font-size: 20px;
        margin-bottom: 4px;
      }

      span {
        font-size: 12px;
        text-align: center;
      }

      .node-actions {
        position: absolute;
        top: -12px;
        right: -12px;
      }
    }

    .connections-svg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;

      .connection-line {
        stroke: #409eff;
        stroke-width: 2;
      }
    }
  }
}

.config-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;

  .panel-header {
    padding: 15px;
    border-bottom: 1px solid #ebeef5;
    h3 {
      margin: 0;
      font-size: 16px;
    }
  }

  .config-content {
    flex: 1;
    padding: 15px;
    overflow-y: auto;
  }
}

.preview-content {
  .preview-canvas {
    position: relative;
    height: 400px;
    background: #fafafa;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    margin-top: 15px;

    .preview-node {
      position: absolute;
      width: 100px;
      height: 50px;
      border-radius: 4px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 12px;

      &.start {
        background: #67c23a;
      }

      &.approval {
        background: #409eff;
      }

      &.condition {
        background: #e6a23c;
      }

      &.copy {
        background: #909399;
      }

      &.end {
        background: #f56c6c;
      }

      i {
        font-size: 16px;
        margin-bottom: 2px;
      }
    }

    .preview-svg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;

      .preview-line {
        stroke: #909399;
        stroke-width: 1;
        stroke-dasharray: 5, 5;
      }
    }
  }
}
</style>
